# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os

from conan import ConanFile
from conan.tools.scm import Git
from conan.tools.files import copy, chdir
from conan.tools.cmake import CMake, CMakeToolchain, cmake_layout

required_conan_version = ">=2.13.0"

class FluentbitConan(ConanFile):
    name = "fluent-bit"
    license = "Apache License V2.0"
    generators = "CMakeDeps"
    description = "Fluent Bit is a fast Log, Metrics and Traces Processor and Forwarder"
    chost = None
    settings = "os", "compiler", "build_type", "arch"
    exports_sources = ["patches/**", "permissions.ini"]

    _cmake = None
    options = {
        "shared": [True, False]
    }
    default_options = {"shared": True}

    def layout(self):
        cmake_layout(self, src_folder="src")

    def source(self):
        source = self.conan_data["sources"][self.version]
        git = Git(self)
        git.fetch_commit(url=source["url"], commit=source["branch"])

    def requirements(self):
        for require in self.conan_data["requires"][self.version]:
            self.requires(require)

    def build_requirements(self):
        for tool_require in self.conan_data["tool_requires"][self.version]:
            self.tool_requires(tool_require)

    def generate(self):
        tc = CMakeToolchain(self)
        # 传递bison环境变量给CMake
        bison_path = os.path.join(self.dependencies.build["bison"].package_folder, "bin", "bison")
        tc.variables["BISON_EXECUTABLE"] = bison_path

        # 传递flex环境变量给CMake
        flex_path = os.path.join(self.dependencies.build["flex"].package_folder, "bin", "flex")
        tc.variables["FLEX_EXECUTABLE"] = flex_path

        tc.extra_cflags.extend(["-D_GNU_SOURCE", "-lm"])
        tc.extra_cxxflags.extend(["-D_GNU_SOURCE", "-lm"])
        tc.variables["CMAKE_SKIP_RPATH"] = True
        tc.variables["BUILD_SHARED"] = self.options.shared
        tc.variables["FLB_MINIMAL"] = "Yes"
        tc.variables["FLB_IN_CPU"] = "Yes"
        tc.variables["FLB_IN_DUMMY"] = "Yes"
        tc.variables["FLB_IN_MEM"] = "Yes"
        tc.variables["FLB_IN_OPENTELEMETRY"] = "Yes"
        tc.variables["FLB_OUT_HTTP"] = "Yes"
        tc.variables["FLB_OUT_OPENTELEMETRY"] = "Yes"
        tc.variables["FLB_OUT_STDOUT"] = "Yes"
        tc.variables["FLB_PROCESSOR_CONTENT_MODIFIER"] = "Yes"

        tc.variables["FLB_WASM"] = "No"
        tc.variables["FLB_LUAJIT"] = "No"
        tc.variables["FLB_BACKTRACE"] = "No"
        lib_path = os.path.join(self.dependencies["libyaml"].package_folder)
        tc.variables["FLB_LIBYAML_DIR"] = lib_path
        tc.variables["FLB_WINDOWS_DEFAULTS"] = "No"
        tc.variables["FLB_PROXY_GO"] = "No"
        tc.variables["FLB_CUSTOM_CALYPTIA"] = "No"
        tc.variables["FLB_PREFER_SYSTEM_LIB_KAFKA"] = "No"
        tc.variables["FLB_EXAMPLES"] = "No"
        tc.variables["FLB_SQLDB"] = "No"
        tc.variables["FLB_REGEX"] = "No"

        if self.settings.arch == "armv8" or self.settings.arch == "x86_64":
            tc.variables["CMAKE_INSTALL_LIBDIR"] = "usr/lib64"
        else:
            tc.variables["CMAKE_INSTALL_LIBDIR"] = "usr/lib"
        if self.options.shared:
            tc.extra_cflags.extend(["-fPIC"])
            tc.extra_cxxflags.extend(["-fPIC"])
        tc.generate()


    def build(self):
        print("============= fluent-bit build begin =============")
        with chdir(self, self.source_folder):
            self.run("sed -i '452a     set(BUILD_SHARED_LIBS ON)' CMakeLists.txt")
            self.run('sed -i \'s|"${FLB_LIBYAML_DIR}/lib"|"${FLB_LIBYAML_DIR}/usr/lib64"|g\' CMakeLists.txt')
            cmake = CMake(self)
            cmake.configure(cli_args=["--no-warn-unused-cli"])
            cmake.build()
        print("============= fluent-bit build end =============")

    def package(self):
        copy(self,
             "libminiz.so*", 
             src=os.path.join(self.build_folder,"lib"), 
             dst=os.path.join(self.package_folder,"usr/lib64"),
        )
        copy(self,
             "fluent-bit", 
             src=os.path.join(self.build_folder,"bin"), 
             dst=os.path.join(self.package_folder,"bin"),
        )
        copy(self, "permissions.ini", src=self.export_sources_folder, dst=self.package_folder)

    def package_info(self):
        self.cpp_info.libdirs = ["usr/lib64"]
        self.cpp_info.libs = ["fluent-bit", "miniz"]
        self.cpp_info.includedirs = ["include"]
        self.runenv_info.append_path(
            "LD_LIBRARY_PATH", os.path.join(self.package_folder, "usr/lib64")
        )
        self.buildenv_info.append_path(
            "LD_LIBRARY_PATH", os.path.join(self.package_folder, "usr/lib64")
        )
        self.buildenv_info.append_path(
            "LD_LIBRARY_PATH", os.path.join(self.package_folder, "lib")
        )
        
   